package org.alex.samples.web;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.alex.samples.model.User;
import org.alex.samples.model.UserVO;
import org.alex.samples.service.IUserService;
import org.alex.samples.util.ExcelUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.context.MessageSource;
import org.springframework.context.i18n.LocaleContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.LocaleResolver;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

@Controller
@RequestMapping({ "/user" })
public class UserController {

	@Autowired
	private IUserService userService;
	@Autowired
	private LocaleResolver localeResolver;
	@Autowired
	private MessageSource messageSource;

	@RequestMapping({ "/changeLocale" })
	public String changeLocale(HttpServletRequest req, HttpServletResponse resp, String localeType) {
		if ("en_US".equals(localeType)) {
			this.localeResolver.setLocale(req, resp, Locale.US);
		} else if ("zh_CN".equals(localeType)) {
			this.localeResolver.setLocale(req, resp, Locale.CHINA);
		}

		return "redirect:/users";
	}

	@RequestMapping({ "/users" })
	public String findAllUsers(Model model) throws Exception {
		List<User> list = this.userService.findAllUsers();
		model.addAttribute("edit",
				this.messageSource.getMessage("page.index.edit", (Object[]) null, LocaleContextHolder.getLocale()));
		model.addAttribute("userList", list);
		return "user/userList";
	}

	@RequestMapping(value = { "/add" }, method = { RequestMethod.GET })
	public String toadd(Model model) {
		model.addAttribute("user", new UserVO());
		return "user/add";
	}

	@RequestMapping(value = { "/add" }, method = { RequestMethod.POST })
	public String addUser(RedirectAttributes redirectAttributes, @Validated UserVO user, BindingResult result) {
		if (result.hasErrors()) {
			return "user/add";
		} else {
			try {
				this.userService.createUser(user);
				redirectAttributes.addFlashAttribute("message", "添加成功");
				return "redirect:/users";
			} catch (Exception var5) {
				var5.printStackTrace();
				return "error";
			}
		}
	}

	@RequestMapping(value = { "/edit/{id}" }, method = { RequestMethod.GET })
	public String toEdit(Model model, @PathVariable String id) {
		try {
			UserVO user = this.userService.getUserById(id);
			model.addAttribute("user", user);
		} catch (Exception var5) {
			var5.printStackTrace();
		}

		return "user/edit";
	}

	@RequestMapping(value = { "/edit/{id}" }, method = { RequestMethod.POST })
	public String editUser(RedirectAttributes redirectAttributes, UserVO user, @PathVariable String id) {
		try {
			user.setId(id);
			this.userService.edtiUser(user);
			redirectAttributes.addFlashAttribute("message", "修改成功");
			return "redirect:/user/users";
		} catch (Exception var5) {
			var5.printStackTrace();
			return "error";
		}
	}

	@RequestMapping(value = { "/delete/{id}" }, method = { RequestMethod.GET })
	public String deleteUser(RedirectAttributes redirectAttributes, @PathVariable String id) {
		try {
			this.userService.deleteUser(id);
			redirectAttributes.addFlashAttribute("message", "删除成功");
		} catch (Exception e) {
			redirectAttributes.addFlashAttribute("message", "删除失败");
			e.printStackTrace();
		}
		return "redirect:/user/users";
	}

	@ResponseBody
	@RequestMapping(value = { "/uploadFile" })
	public Map<String, String> uploadFile(@RequestParam(name = "uploadFile")MultipartFile[] uploadFile,
			HttpSession session) throws Exception {
		MultipartFile uploadSimpleFile = uploadFile[0];
		Map<String, String> messageMap = new HashMap<String, String>();
		String fileName = uploadSimpleFile.getOriginalFilename();

		// 获取文件后缀名
		String postfix = fileName.substring(fileName.lastIndexOf('.'));

		try {
			if (ExcelUtils.OFFICE_EXCEL_2003_POSTFIX.equals(postfix) || ExcelUtils.OFFICE_EXCEL_2007_POSTFIX.equals(postfix)) {
				userService.saveUserByExcel(uploadSimpleFile.getInputStream(), postfix);
				messageMap.put("message", "true");
			} else {
				messageMap.put("message", "文件格式不正确");
			}
		} catch (IOException e) {
			e.printStackTrace();
			messageMap.put("message", "批量导入失败");
		}
		return messageMap;
	}
	


	@InitBinder
	public void initBinder(WebDataBinder binder) {
		SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
		dateFormat.setLenient(false);
		binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, true));
	}
}